import React, { useState, useEffect } from 'react';
import { Layout, Menu, theme, Avatar, Dropdown, Space, Badge, message } from 'antd';
import type { MenuProps } from 'antd';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
  DashboardOutlined,
  SettingOutlined,
  LogoutOutlined,
  BellOutlined,
  MessageOutlined,
  TeamOutlined,
  EyeOutlined,
  FileImageOutlined,
  ScheduleOutlined,
  BarChartOutlined,
  SwapOutlined,
} from '@ant-design/icons';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { useAccountStore } from '../stores/accountStore';

const { Header, Sider, Content } = Layout;

type MenuItem = Required<MenuProps>['items'][number];

// 菜单路径映射
const menuPathMap: Record<string, string> = {
  'dashboard': '/dashboard',
  'accounts': '/accounts',
  'competitor': '/competitor',
  'content': '/content',
  'content-materials': '/content',
  'content-drafts': '/content',
  'publish': '/publish',
  'analytics': '/analytics',
  'settings': '/settings',
};

// 菜单配置
const menuItems: MenuItem[] = [
  {
    key: 'dashboard',
    icon: <DashboardOutlined />,
    label: '仪表盘',
  },
  {
    key: 'accounts',
    icon: <TeamOutlined />,
    label: '账号管理',
  },
  {
    key: 'competitor',
    icon: <EyeOutlined />,
    label: '竞品分析',
  },
  {
    key: 'content',
    icon: <FileImageOutlined />,
    label: '内容管理',
    children: [
      {
        key: 'content-materials',
        label: '素材管理',
      },
      {
        key: 'content-drafts',
        label: '草稿箱',
      },
    ],
  },
  {
    key: 'publish',
    icon: <ScheduleOutlined />,
    label: '发布管理',
  },
  {
    key: 'analytics',
    icon: <BarChartOutlined />,
    label: '数据分析',
  },
  {
    key: 'settings',
    icon: <SettingOutlined />,
    label: '系统设置',
  },
];

const MainLayout: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  const { 
    accounts, 
    currentAccount, 
    fetchAccounts, 
    switchCurrentAccount 
  } = useAccountStore();

  useEffect(() => {
    fetchAccounts();
  }, [fetchAccounts]);

  // 根据当前路径找到对应的菜单项
  const findMenuKey = (pathname: string): string => {
    for (const [key, path] of Object.entries(menuPathMap)) {
      if (path === pathname) {
        return key;
      }
    }
    return 'dashboard';
  };

  // 处理菜单点击
  const handleMenuClick = ({ key }: { key: string }) => {
    const path = menuPathMap[key];
    if (path) {
      navigate(path);
    }
  };

  // 处理账号切换
  const handleAccountSwitch = async (accountId: string) => {
    try {
      await switchCurrentAccount(accountId);
      message.success('切换账号成功');
    } catch (error) {
      console.error('切换账号失败:', error);
      message.error('切换账号失败');
    }
  };

  // 处理跳转到账号管理
  const handleGoToAccounts = () => {
    navigate('/accounts');
  };

  // 生成用户菜单项
  const generateUserMenuItems = (): MenuProps['items'] => {
    const items: MenuProps['items'] = [];
    
    // 添加当前账号信息
    if (currentAccount) {
      items.push({
        key: 'current-account',
        label: (
          <div style={{ padding: '8px 0' }}>
            <div style={{ fontWeight: 'bold' }}>当前账号</div>
            <div style={{ fontSize: '12px', color: '#666' }}>
              {currentAccount.nickname}
            </div>
          </div>
        ),
        disabled: true,
      });
      
      items.push({
        type: 'divider',
      });
    }

    // 添加可切换的账号（最多3个）
    const activeAccounts = accounts
      .filter(account => account.status === 'active' && account.id !== currentAccount?.id)
      .slice(0, 3);

    activeAccounts.forEach(account => {
      items.push({
        key: `switch-${account.id}`,
        icon: <SwapOutlined />,
        label: account.nickname,
        onClick: () => handleAccountSwitch(account.id),
      });
    });

    // 如果有其他账号，添加分割线
    if (activeAccounts.length > 0) {
      items.push({
        type: 'divider',
      });
    }

    // 添加账号管理入口
    items.push({
      key: 'account-management',
      icon: <TeamOutlined />,
      label: '账号管理',
      onClick: handleGoToAccounts,
    });

    // 添加退出登录
    items.push({
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    });

    return items;
  };

  // 处理用户菜单点击
  const handleUserMenuClick = ({ key }: { key: string }) => {
    switch (key) {
      case 'logout':
        // 处理退出登录
        localStorage.removeItem('token');
        navigate('/dashboard');
        break;
    }
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div style={{ 
          height: 32, 
          margin: 16, 
          background: 'rgba(255, 255, 255, 0.2)',
          borderRadius: 6,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: 'white',
          fontSize: 16,
          fontWeight: 'bold'
        }}>
          {collapsed ? 'CR' : 'Cool Red AI'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[findMenuKey(location.pathname)]}
          items={menuItems}
          onClick={handleMenuClick}
        />
      </Sider>
      <Layout>
        <Header style={{ padding: 0, background: colorBgContainer }}>
          <div style={{ 
            display: 'flex', 
            justifyContent: 'space-between', 
            alignItems: 'center',
            height: '100%',
            padding: '0 24px'
          }}>
            <div>
              {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                className: 'trigger',
                onClick: () => setCollapsed(!collapsed),
                style: { fontSize: 18 }
              })}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <Badge count={5}>
                <BellOutlined style={{ fontSize: 18, cursor: 'pointer' }} />
              </Badge>
              <Badge count={2}>
                <MessageOutlined style={{ fontSize: 18, cursor: 'pointer' }} />
              </Badge>
              <Dropdown
                menu={{
                  items: generateUserMenuItems(),
                  onClick: handleUserMenuClick,
                }}
                placement="bottomRight"
                trigger={['click']}
              >
                <Space style={{ cursor: 'pointer' }}>
                  <Avatar icon={<UserOutlined />} />
                  <span>
                    {currentAccount ? currentAccount.nickname : '管理员'}
                  </span>
                </Space>
              </Dropdown>
            </div>
          </div>
        </Header>
        <Content
          style={{
            margin: '24px 16px',
            padding: 24,
            minHeight: 280,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
          }}
        >
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
};

export default MainLayout; 